package com.cars.satoken.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson2.JSON;
import com.cars.satoken.entities.User;
import com.cars.satoken.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: caoqianfan
 * @date: 2023/11/20 10:27
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/add")
    public SaResult add(@RequestBody User user) {
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12)));
        if (userService.save(user)) {
            return SaResult.ok();
        }
        return SaResult.error();
    }

    @DeleteMapping("/delete")
    public SaResult delete(@RequestBody User user) {
        if (!StpUtil.isSafe("user-delete")) {
            return SaResult.error("用户删除失败，请完成二级认证后再次访问接口");
        }
        if (userService.removeById(user)) {
            return SaResult.ok("用户删除成功");
        }
        return SaResult.error();
    }

    @PutMapping("/update")
    public SaResult update(@RequestBody User user) {
        user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt(12)));
        if (userService.updateById(user)) {
            return SaResult.ok();
        }
        return SaResult.error();
    }

    @GetMapping("/getById")
    public SaResult getById(@RequestParam Long id) {
        User userDO = userService.getById(id);
        if (userDO != null) {
            return SaResult.ok(JSON.toJSONString(userDO));
        }
        return SaResult.error("不存在该用户!");
    }

    @GetMapping("/list")
    public SaResult list() {
        List<User> userList = userService.list();
        if (!userList.isEmpty()) {
            return SaResult.ok(JSON.toJSONString(userList));
        }
        return SaResult.error("用户列表为空!");
    }

    // 提供密码进行二级认证
    @RequestMapping("openSafe")
    public SaResult openSafe(String password) {
        User user = StpUtil.getSession().getModel("current-user", User.class);
        // 比对密码（此处只是举例，真实项目时可拿其它参数进行校验）
        if (user.getPassword().equals(password)) {
            // 比对成功，为当前会话打开二级认证，有效期为120秒
            StpUtil.openSafe("user-delete", 120);
            return SaResult.ok("二级认证成功");
        }
        // 如果密码校验失败，则二级认证也会失败
        return SaResult.error("二级认证失败");
    }
}